package gincsrf

import (
    "html/template"
    "net/http"

    "github.com/gin-gonic/gin"
    "github.com/gorilla/csrf"
)

func asGin(middleware func(next http.Handler) http.Handler) gin.HandlerFunc {
    return func(gctx *gin.Context) {
        var skip = true
        var handler http.HandlerFunc = func(http.ResponseWriter, *http.Request) {
            skip = false
        }
        middleware(handler).ServeHTTP(gctx.Writer, gctx.Request)
        switch {
        case skip:
            gctx.Abort()
        default:
            gctx.Next()
        }
    }
}

func New(authKey []byte, errHandler http.HandlerFunc) gin.HandlerFunc {
    opts := []csrf.Option{

        csrf.SameSite(csrf.SameSiteStrictMode),

        csrf.RequestHeader("Authenticity-Token"),

        csrf.FieldName("authenticity_token"),
    }
    if errHandler != nil {
        opts = append(opts,

            csrf.ErrorHandler(errHandler),
        )
    }
    return asGin(csrf.Protect(authKey, opts...))
}

func Token(c *gin.Context) string {
    return csrf.Token(c.Request)
}

func TemplateField(c *gin.Context) template.HTML {
    return csrf.TemplateField(c.Request)
}

func SetHeader(c *gin.Context) {
    c.Header("X-CSRF-Token", csrf.Token(c.Request))
}
